<?php

namespace Gql\ScalarType;

use Exception;
use Gql\Contracts\TypeAbstract;
use GraphQL\Error\Error;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Utils\Utils;
use function is_int;
use function is_object;
use function is_scalar;
use function is_string;

class ImgType extends TypeAbstract
{

    /** @var string */
    public $description =
        ' 图片类型 ';

    /**
     * @param mixed $value
     *
     * @return string
     *
     * @throws Error
     */
    public function serialize($value)
    {
        if (!$value) {
            return '';
        }
        if (!is_scalar($value) && (!is_object($value) || !method_exists($value, '__toString'))) {
            throw new Error('Img type cannot represent non scalar value: ' . Utils::printSafe($value));
        }

        return (string)$value;
    }

    /**
     * @param mixed $value
     *
     * @return string
     *
     * @throws Error
     */
    public function parseValue($value)
    {
        throw new Error('Cannot represent value as Img: ' . Utils::printSafe($value));
    }

    /**
     * @param Node $valueNode
     * @param mixed[]|null $variables
     *
     * @return string|null
     *
     * @throws Exception
     */
    public function parseLiteral($valueNode, ?array $variables = null)
    {

//        Request::file('avatar')->store('avatars');
        if (is_string($valueNode) || is_int($valueNode)) {
            return $valueNode;
        }
        if ($valueNode instanceof StringValueNode || $valueNode instanceof IntValueNode) {
            return $valueNode->value;
        }

        // Intentionally without message, as all information already in wrapped Exception
        throw new \Exception();
    }
}
